<template>
	<view>
		<mc-framework navTitle="MES工控机" @changeLevel="changeLevel">
			<template #content>
				<view class="content" style="height: 100%;">
					<view class="contentBox">
						<view class="container">
							<uni-forms ref="baseForm" :modelValue="baseFormData">
								<view class="form-item-row">

									<uni-forms-item label="单据编号:" label-width="auto" disabled>
										<input v-model="baseFormData.BillNo" type="text" placeholder="自动带出单据编号"
											disabled />
									</uni-forms-item>
									<uni-forms-item label="单据日期:" label-width="auto" disabled>
										<input v-model="baseFormData.BillDate" type="text" placeholder="单据日期"
											disabled />
									</uni-forms-item>

									<!-- 下拉 -->
									<uni-forms-item label="检验类型:" label-width="auto">
										<input v-model="baseFormData.InspectionType" type="text" disabled
											placeholder="请选择检验类型" />
										<text class='text' @click="addgetInspectionType"></text>
									</uni-forms-item>

									<uni-forms-item label="检验单号:" label-width="auto">
										<input v-model="baseFormData.JYBillNo" type="text" disabled
											placeholder="自动带出检验单号" />
									</uni-forms-item>

									<uni-forms-item label="派工单编号:" label-width="auto">
										<input v-model="baseFormData.PGBillNo" type="text" disabled
											placeholder="自动带出派工单编号" />
									</uni-forms-item>

									<uni-forms-item label="产品名称:" label-width="auto">
										<input v-model="baseFormData.ProductName" type="text" disabled
											placeholder="自动带出产品名称" />
									</uni-forms-item>

									<uni-forms-item label="送检数量:" label-width="auto">
										<input v-model="baseFormData.CkAmount" type="text" disabled
											placeholder="自动带出送检数量" />
									</uni-forms-item>
									<uni-forms-item label="申请人:" label-width="auto">
										<input v-model="baseFormData.Declarer" type="text" disabled
											placeholder="自动带出申请人" />
									</uni-forms-item>


									<uni-forms-item label="抽样次数:" label-width="auto">
										<input v-model="baseFormData.SamplingCount" type="text" placeholder="请输入抽样次数" />
									</uni-forms-item>
									<uni-forms-item label="抽样数量:" label-width="auto">
										<input v-model="baseFormData.SamplingAmount" type="number"
											placeholder="请输入抽样数量" />
									</uni-forms-item>
									<uni-forms-item label="抽样合格数量:" label-width="auto">
										<input v-model="baseFormData.SamplingOKAmount" type="number"
											placeholder="请输入抽样合格数量" />
									</uni-forms-item>
									<uni-forms-item label="抽样不合格数量:" label-width="auto">
										<input v-model="baseFormData.SamplingBadAmount" type="number"
											style="width: 32vw;" placeholder="请输入抽样不合格数量" />
									</uni-forms-item>

									<uni-forms-item label="异常描述:" label-width="auto">
										<input v-model="baseFormData.GZContent" type="text" placeholder="请输入异常描述" />
									</uni-forms-item>
									<uni-forms-item label="现场照片:" label-width="auto" style="width: 100%;"
										class="uni_forms_item">
										<u-upload :fileList="DImgs" @afterRead="afterRead" @delete="deletePic" multiple
											:maxCount="5" :previewFullImage="true"></u-upload>
									</uni-forms-item>

								</view>
							</uni-forms>

						</view>

					</view>

					<view class="DetailsbottomBtns">

						<button class="button1" block @click="submit">
							{{changeButton}}
						</button>
					</view>
					<u-datetime-picker :show="show" v-model="value1" mode="date" @cancel='show=false'
						@confirm='pickerConfirm'></u-datetime-picker>


					<u-action-sheet :actions="showNameList" :show="showName" @select="addName"
						@close="showName=false"></u-action-sheet>
					<u-action-sheet :actions="InspectionTypeList" :show="InspectionTypeShow"
						@select="InspectionTypeClick" @close="InspectionTypeShow=false"></u-action-sheet>

					<u-toast ref="uToast"></u-toast>
					<u-popup :show="popup_logout" mode="center" :closeOnClickOverlay="false" :round="4">
						<view class="popup-content">
							<view class="popup-content_close x-c">
								<uni-icons type="closeempty" color="#999" size="20"
									@click='popup_logout = false'></uni-icons>
							</view>
							<view class="x-c title">
								<text>{{popuptitle}}</text>
							</view>
							<view class="contentView">
								<text>{{popupcontent}}</text>
							</view>
							<view class="btnBox x-ac">
								<u-button type="primary" text="确定" @click="confirmClick"></u-button>
							</view>
						</view>
					</u-popup>

				</view>
			</template>

		</mc-framework>
	</view>
</template>

<script>
	import {
		getTimeStamp,
		getFormatDateTime,
		getBefore7DateTime
	} from '@/mes/common/base.js';
	export default {
		data() {
			return {
				popuptitle: '',
				popupcontent: '',
				popup_logout: false,
				DImgs: [],
				serverIP: '',
				baseFormData: {
					JYBillNo: '',
					InspectionID: null,
					FType: "",
					BillNO: "",
					PGBillNo: "",
					CkAmount: null,
					ProductID: null,
					ProductName: "",
					InspectionType: null,
					BillDate: '',
					Declarer: '',
					SamplingCount: '',
					SamplingAmount: '',
					SamplingOKAmount: '',
					SamplingBadAmount: '',
					GZContent: ''

				},
				DImgs: [],
				sexs: [{
					text: '合格',
					value: 0
				}, {
					text: '不合格',
					value: 1
				}],
				TimeName: '',
				show: false,
				value1: Number(new Date()),
				showName: false,
				showNameList: [],
				changeName: '',
				changeButton: '保存',

				InspectionTypeShow: false,
				InspectionTypeList: []
			};
		},
		mounted() {},
		onLoad(onload) {
			let that = this;
			var item = JSON.parse(onload.item)
			if (item.FaultDocID) {
				that.queryList(item.FaultDocID)
			} else {
				this.baseFormData = item
				this.baseFormData.Declarer = this.baseFormData.Declarer ? this.baseFormData.Declarer : this
					.$store.state.UserInfo.UserName
				this.baseFormData.StartEmplID = this.baseFormData.StartEmplID ? this.baseFormData.StartEmplID : this.$store
					.state.UserInfo.EmplID
				this.baseFormData.EquipmentName = this.baseFormData.EquipmentName ? this.baseFormData.EquipmentName : this
					.$store.state.GuyueModule.MesBasicInfo.warehouse.EquipmentName
				this.baseFormData.EquipmentID = this.baseFormData.EquipmentID ? this.baseFormData.EquipmentID : this
					.$store.state.GuyueModule.MesBasicInfo.warehouse.EquipmentID
				this.baseFormData.BillDate = this.baseFormData.BillDate ? this.baseFormData.BillDate :
					getFormatDateTime(new Date())
				if (that.baseFormData.FaultTypeID == 1) {
					that.baseFormData.FaultTypeName = '设备故障'
				} else if (that.baseFormData.FaultTypeID == 2) {
					that.baseFormData.FaultTypeName = '模具故障'
				} else {
					that.baseFormData.FaultTypeName = '工艺故障'
				}
				if (that.baseFormData.FType == 'SJJ') {
					that.baseFormData.FaultTypeName = '首件检'
				}
			}


		},
		onBackPress(options) { // 监听页面返回
			if (options.from == 'navigateBack') { // 通过点击路由返回
				return false;
			} else if (options.from == 'backbutton') { // 通过外置返回
				return true;
			}
		},
		methods: {
			confirmClick() {
				this.popup_logout = false
			},
			deletePic(event) {
				this.DImgs.splice(event.index, 1);
			},
			async afterRead(event) {
				let lists = [].concat(event.file)
				console.log(event);
				let fileListLen = this.DImgs.length;
				lists.map((item) => {
					this.DImgs.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})

				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.DImgs[fileListLen]
					this.DImgs.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},

			uploadFilePromise(url) {
				let that = this;
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: 'http://' + that.Request
							.serverIP() + '/Frame/uploadFile?dirName=' + '故障现场',
						filePath: url,
						name: 'file',
						header: {
							'Content-Type': 'multipart/form-data' // 必须设置
						},
						formData: {
							user: 'test'
						},
						success: (uploadFileRes) => {
							const data = JSON.parse(uploadFileRes.data);
							// console.log(data);
							resolve(data.data)
						}
					});
				})
			},

			InspectionTypeClick(e) {
				let that = this;
				console.log(e);
				this.InspectionTypeShow = false
				that.baseFormData.InspectionType = e.NAME
				this.$forceUpdate()
			},
			addgetInspectionType() {
				let that = this;
				if (that.baseFormData.InspectionID) {
					that.Request.request('getInspectionDetail', {
						InspectionID: that.baseFormData.InspectionID
					}, (ret) => {
						console.log(JSON.stringify(ret))
						that.baseFormData.FType = ret.data.ds[0].FType
						if (ret.status == 200 && ret.data.ds.length > 0) {
							that.Request.request('getInspectionType', {
								ID: that.baseFormData.FType
							}, (ret) => {
								console.log(JSON.stringify(ret))
								if (ret.status == 200 && ret.data.ds.length > 0) {
									ret.data.ds.map(item => item.name = item.NAME)
									that.InspectionTypeList = ret.data.ds
									that.InspectionTypeShow = true
								}
							})
						}
					})
				}
			},

			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.DImgs.length;
				lists.map((item) => {
					this.DImgs.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})

				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.DImgs[fileListLen]
					this.DImgs.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},

			uploadFilePromise(url) {
				let that = this;
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: 'http://' + that.Request
							.serverIP() + '/Frame/uploadFile?dirName=' + '故障现场',
						filePath: url,
						name: 'file',
						header: {
							'Content-Type': 'multipart/form-data' // 必须设置
						},
						formData: {
							user: 'test'
						},
						success: (uploadFileRes) => {
							const data = JSON.parse(uploadFileRes.data);
							console.log(data);
							resolve(data.data)
						}
					});
				})
			},
			addName(e) {
				var that = this
				console.log(e);
				that.baseFormData.QCEmplID = e.EmplID
				that.baseFormData.QCEmplName = e.EmplName
				that.showName = false
				this.$forceUpdate()
			},

			changebuttons(ID) {
				if (ID == 0) {
					this.changeButton = '开工'
				} else {
					this.changeButton = '保存'

				}
			},


			// 获取时间
			pickerConfirm(e) {
				var time = getFormatDateTime(e.value)
				this.baseFormData.BillDate = time
				this.show = false
				this.$forceUpdate()
			},

			// 保存
			submit() {
				var that = this;
				var show = true
				var msg
				console.log(this.baseFormData);

				if (that.baseFormData.InspectionType == '' || that.baseFormData.InspectionType == null) {
					msg = '请输入检验类型'
					show = false
				} else if (that.baseFormData.SamplingCount == '' || that.baseFormData.SamplingCount == null) {
					msg = '请输入抽样次数'
					show = false
				} else if (that.baseFormData.SamplingAmount == '' || that.baseFormData.SamplingAmount == null) {
					msg = '请输入抽样数量'
					show = false
				} else if (that.baseFormData.SamplingOKAmount == '' || that.baseFormData.SamplingOKAmount == null) {
					msg = '请输入抽样合格数量'
					show = false
				} else if (that.baseFormData.SamplingBadAmount == '' || that.baseFormData.SamplingBadAmount == null) {
					msg = '请输入抽样不合格数量'
					show = false
				} else if (that.baseFormData.GZContent == '' || that.baseFormData.GZContent == null) {
					msg = '请输入异常描述'
					show = false
				}
				if (show) {
					const prefix = 'http://' + that.Request.serverIP();
					console.log(that.DImgs);
					that.DImgs.map(obj => {
						if (typeof obj.url === 'string' && obj.url.startsWith(prefix)) {
							obj.url = obj.url.replace(prefix, '');
						}
						return obj;
					});
					console.log(that.DImgs);
					var obj = {
						JYBillNo: that.baseFormData.JYBillNo ? that.baseFormData.JYBillNo : 0,
						BillDate: that.baseFormData.BillDate,
						InspectionType: that.baseFormData.InspectionType,
						BillNO: that.baseFormData.BillNO,
						PGBillNo: that.baseFormData.PGBillNo,
						ProductName: that.baseFormData.ProductName,
						CkAmount: that.baseFormData.CkAmount,
						Declarer: that.baseFormData.Declarer,
						SamplingCount: that.baseFormData.SamplingCount,
						SamplingAmount: that.baseFormData.SamplingAmount,
						SamplingOKAmount: that.baseFormData.SamplingOKAmount,
						SamplingBadAmount: that.baseFormData.SamplingBadAmount,
						GZContent: that.baseFormData.GZContent,
						FilePath1: that.DImgs.map(item => item.url).join(','),
						FaultDocID: that.baseFormData.FaultDocID ? that.baseFormData.FaultDocID : 0,
						BillType: 'PZYC',
						Source: that.baseFormData.InspectionID
					}
					console.log(obj);
					that.Request.request('saveFaultDoc', obj, function(ret) {
						console.log(ret);
						if (ret.status == 200) {
							that.$refs.uToast.show({
								title: '保存',
								type: 'success',
								message: '保存成功'
							})
							setTimeout(() => {
								that.queryList(ret.data.ds[0].FaultDocID)
							}, 1000)

						}
					})

				} else {

					that.popuptitle = '报错'
					that.popupcontent = msg
					that.popup_logout = true
				}
			},
			queryList(id) {
				var that = this
				try {
					that.Request.request('getFaultDocDetail', {
						FaultDocID: id
					}, (ret) => {
						console.log(ret.data);
						var stringArray = ret.data.ds[0].FilePath1.split(',')
						if (stringArray[0] != '' && stringArray.length > 0) {
							that.DImgs = stringArray.map(item => ({
								url: 'http://' + that.Request.serverIP() + item.trim()
							}));
						}
						that.baseFormData = ret.data.ds[0]

						// item.BillDate = item.BillDate ? item.BillDate.replace('T', ' ') : ''
						that.baseFormData.BillDate = ret.data.ds[0].BillDate ? ret.data.ds[0].BillDate.replace('T',
							' ') : ''
						if (that.baseFormData.FaultDocID) {
							that.titleShow = true
						}
						that.$forceUpdate()
					})
				} catch (e) {
					console.log(e)
					this.$utils.hideLoading();
					this.$utils.msg('请求失败请重试')
				}
			},
			// 跳转tag
			changeLevel(data, row) {

				let routes = getCurrentPages(); //当前页面栈

				let backIndex = routes.length - row.length; // 计算返回页面栈数
				if (backIndex == 1) {
					let prevPage = routes[routes.length - 2]
					prevPage.$vm.getList()
				}
				uni.navigateBack({
					delta: backIndex
				})
			},

		}
	}
</script>

<style lang="scss">
	@import "../css/index.css";


	.form-item-row {
		display: flex;
		flex-wrap: wrap;

		.uni-forms-item {
			width: 46%;
			margin: 0.3% 2%;

			input {
				height: 100%;
				width: 34vw;
				border-bottom: 2px solid #51d0d0;
			}
		}

		.uni_forms_item {
			width: 100%;
			display: flex;
			align-items: center;

			.u-upload {
				width: 83vw;
				float: right;
			}

			// ::v-deep.u-icon__icon {
			// 	font-size: 20rpx !important;
			// }
		}

	}
</style>